package cn.hsp.chargemagic

import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import cn.hsp.chargemagic.BatteryListener.BatteryStateListener
import kotlinx.android.synthetic.main.activity_main.*
import java.util.*
import kotlin.concurrent.fixedRateTimer

/**
 * @author 花生皮编程(CSDN、简书、掘金、今日头条、微信公众号、抖音、快手、B站、西瓜视频)
 * @关于作者 https://juejin.cn/post/7002792005688360968
 */
class HspActivity : AppCompatActivity() {
    private lateinit var listener: BatteryListener
    private var i = 0;
    private var timer: Timer? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        listener = BatteryListener(this)
        listener.register(object : BatteryStateListener {
            override fun onStateChanged() {}

            override fun onStateLow() {}

            override fun onStateOkay() {}

            override fun onStatePowerConnected() {
                startTimer()
            }

            override fun onStatePowerDisconnected() {
                stopTimer()
            }
        })
    }

    private fun startTimer() {
        timer = fixedRateTimer("", false, 0, 100) {
            i += 666
            runOnUiThread {
                textView.text = getString(R.string.money_amount, i)
            }
        }
    }

    private fun stopTimer() {
        timer?.cancel()
    }

    override fun onDestroy() {
        listener.unregister()
        super.onDestroy()
    }
}